﻿using MCMesServer.PublicLogInfo;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace MCMesServer.DBFunctions.TransformFuncs
{
    public class TransformModelFunc<T>
    {
        public static string TransformModel2StringFunc(T t)
        {
            try
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, t);
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                string dataString = Encoding.UTF8.GetString(dataBytes);
                return dataString;
            }
            catch (Exception ex)
            {
                PublicLogInfoFunc.RecordManualErrorMessage(t.ToString() + "转换为String", ex.Message);
                return "Error";
            }
        }

        public static T TransformString2ModelFunc(string dto)
        {
            byte[] data = Encoding.UTF8.GetBytes(dto);
            var mStream = new MemoryStream(data);
            var serializer = new DataContractJsonSerializer(typeof(T));
            T t = (T)serializer.ReadObject(mStream);
            return t;
        }
    }
}
